<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <script type="module">
      import '../bundle.js';
    </script>
    <style>
      html,
      body {
        margin: 10;
        margin-top: 20;
      }
    </style>
  </head>
  <body>
    <h3>
      This page is used to test Compound-Container Luigi Client API functionalities for
      compound web component based microfrontend
    </h3>
    <button id="luigi-update-context" type="button">Update context</button>
    <span id="cc-ctx" style="display: none"></span>

    <!-- base scenario compound container-->
    <span>Below is a compound container example for testing functionality</span>
    <div style="border: solid 1px blue">
      <luigi-compound-container
        data-test-id="luigi-client-api-test-compound-01"
        id="dashboard"
        active-feature-toggle-list='["ft1", "ft2"]'
        context='{"label": "Dashboard"}'
        node-params='{"Luigi":"rocks"}'
        search-params='{"test":"searchParam1"}'
        path-params='{"path":"param"}'
        client-permissions='{"permission": "testPermission"}'
        user-settings='{"language":"it", "date":""}'
        anchor="testAnchorCompound"
        defer-init="false"
        skip-init-check="true"
        webcomponent="true"
        theme="sap_fiori_3"
        locale="en"
      ></luigi-compound-container>
    </div>

    <!-- luigi-client-init scenario wc container-->
    <button id="luigi-client-init-button" style="margin: 25px 0 10px">
      this.LuigiClient.luigiClientInit();
    </button>
    <div style="border: solid 1px red; height: 150px">
      <luigi-compound-container
        id="luigi-client-init-test"
        webcomponent="true"
        context='{"content":" -- luigi-client-init-test --"}'
        anchor="testAnchorCompound"
        user-settings='{"language":"it", "date":""}'
        theme="sap_fiori_3"
        defer-init="false"
      ></luigi-compound-container>
    </div>

    <!-- defer-init scenario wc container-->
    <button id="defer-init-button" style="margin: 25px 0 10px">
      container.init() - click to initialize defered compound wc
    </button>
    <div style="border: solid 1px red; height: 100px">
      <luigi-compound-container
        id="defer-init-test"
        webcomponent="true"
        context='{"content":" -- defer-init test --"}'
        defer-init="true"
      ></luigi-compound-container>

      <!-- Used for testing dynamic compound container creation -->
      <div class="content"></div>
    </div>

    <script type="module">
      import MFEventID from '../bundle.js';

      const compoundContainer = document.getElementById('dashboard');

      compoundContainer.addEventListener(MFEventID.CUSTOM_MESSAGE, (e) => {
        console.debug('CUSTOM_MESSAGE Listener picked up: ', e.detail);
        if (event.detail.id !== 'timer') {
          alert(MFEventID.CUSTOM_MESSAGE + ': ' + event.detail.id);
        }
      });

      compoundContainer.compoundConfig = {
        renderer: {
          use: 'grid',
          config: {
            columns: '1fr 1fr 1fr 2fr',
            layouts: [
              {
                minWidth: 0,
                maxWidth: 600,
                columns: '1fr',
                gap: 0,
              },
              {
                minWidth: 600,
                maxWidth: 1024,
                columns: '1fr 1fr',
                gap: '30px',
              },
            ],
          },
        },
        children: [
          {
            viewUrl: '../assets/panelHeader.js',
            context: {
              title: 'My Awesome Grid 000',
              description: 'Really awesome',
            },
            layoutConfig: {
              row: '1',
              column: '1 / -1',
            },
            eventListeners: [
              {
                source: 'input1',
                name: 'sendInput',
                action: 'update',
                dataConverter: (data) => {
                  console.info(
                    'dataConverter(): Received Custom Message from "input1" MF ' + data,
                  );
                  return 'new text: ' + data;
                },
              },
            ],
          },
          {
            id: 'input1',
            viewUrl: './compound/helloWorldWC.js',
            context: {
              title: 'Some input',
              instant: true,
            },
          },
          {
            viewUrl: '../assets/mfeMain.js',
            context: {
              label: 'Another web component',
            },
          },
          {
            id: 'timerMFE',
            viewUrl: '../assets/timer.js',
            context: {
              min: 2,
              fontScale: '0.5',
            },
          },
          {
            viewUrl: '../assets/mfeMain.js',
            context: {
              label: 'My Label',
            },
          },
          {
            viewUrl: '../assets/panelFooter.js',
            context: {
              footer: 'This is the end of awesomeness',
            },
            layoutConfig: {
              column: '1 / -1',
            },
          },
        ],
      };

      var alertSettings = {};

      const showAnAlert = (alertSettings, luigiContainer) => {
        var popup = document.createElement('div');
        var text = document.createTextNode(alertSettings.settings.text);
        popup.appendChild(text);

        var dismissButton = document.createElement('BUTTON');
        dismissButton.setAttribute('id', 'dismissAlert');
        var buttonText = document.createTextNode('Dismiss Alert');
        dismissButton.addEventListener('click', () => {
          console.log(
            'Dismiss clicked core side. Sending close message to mf of id =',
            alertSettings.settings.id,
          );
          luigiContainer.notifyAlertClosed(
            alertSettings.settings.id,
            'neverShowItAgain from wc',
          );
          popup.style.display = 'none';
        });
        dismissButton.appendChild(buttonText);
        const closeButton = document.createElement('button');
        if (alertSettings.settings.notifyAlertClosed) {
          closeButton.innerHTML = 'Close Alert using notifyAlertClosed';
        } else {
          closeButton.innerHTML = 'Close Alert';
        }
        closeButton.setAttribute('id', 'closeAlert');
        closeButton.addEventListener('click', () => {
          if (alertSettings.settings.notifyAlertClosed) {
            luigiContainer.notifyAlertClosed(alertSettings.settings.id);
          } else {
            luigiContainer.notifyAlertClosed(alertSettings.settings.id);
          }
          popup.style.display = 'none';
        });
        popup.appendChild(dismissButton);
        popup.appendChild(closeButton);

        popup.style.visibility = 'visible';
        popup.id = 'pop';
        document.getElementsByTagName('body')[0].appendChild(popup);
        return dismissButton;
      };

      compoundContainer.init();
      compoundContainer.addEventListener(MFEventID.NAVIGATION_REQUEST, (event) => {
        console.log(event.detail);
        window.location.hash = event.detail.link;
      });
      compoundContainer.addEventListener(MFEventID.GO_BACK_REQUEST, (event) => {
        console.log(event.detail);
        alert(event.detail.goBackValue);
      });
      compoundContainer.addEventListener(
        MFEventID.UPDATE_TOP_NAVIGATION_REQUEST,
        (event) => {
          alert('UPDATE_TOP_NAVIGATION_REQUEST event received');
        },
      );
      compoundContainer.addEventListener(
        MFEventID.UPDATE_MODAL_PATH_DATA_REQUEST,
        (event) => {
          alert(
            `LuigiClient.linkManager().updateModalPathInternalNavigation("${event.detail.link}")`,
          );
        },
      );
      compoundContainer.addEventListener(
        MFEventID.SHOW_CONFIRMATION_MODAL_REQUEST,
        (event) => {
          const data = event.detail;
          const val = confirm(data.body);
          compoundContainer.notifyConfirmationModalClosed(val);
        },
      );
      compoundContainer.addEventListener(
        MFEventID.RUNTIME_ERROR_HANDLING_REQUEST,
        (event) => {
          console.log(event.detail);
        },
      );
      compoundContainer.addEventListener(MFEventID.ADD_NODE_PARAMS_REQUEST, (event) => {
        const params = event.detail.params;
        console.log('params', params);
      });
      compoundContainer.addEventListener(MFEventID.SET_ANCHOR_LINK_REQUEST, (event) => {
        console.log('anchor', event.detail);
      });
      compoundContainer.addEventListener(MFEventID.SET_DIRTY_STATUS_REQUEST, (event) => {
        console.log('dirty', event.detail);
        alert('LuigiClient.uxManager().setDirtyStatus()=' + event.detail.dirty);
      });
      compoundContainer.addEventListener(
        MFEventID.SET_CURRENT_LOCALE_REQUEST,
        (event) => {
          console.log('locale', event.detail);
          alert(
            'LuigiClient.uxManager().setCurrentLocale()=' + event.detail.currentLocale,
          );
        },
      );
      compoundContainer.addEventListener(
        MFEventID.OPEN_USER_SETTINGS_REQUEST,
        (event) => {
          console.log('Open User Settings Request received', event.detail);
          alert('LuigiClient.uxManager().openUserSettings()');
        },
      );
      compoundContainer.addEventListener(
        MFEventID.CLOSE_USER_SETTINGS_REQUEST,
        (event) => {
          console.log('Close User Settings Request received', event.detail);
          alert('LuigiClient.uxManager().closeUserSettings()');
        },
      );
      compoundContainer.addEventListener(MFEventID.REMOVE_BACKDROP_REQUEST, (event) => {
        console.log('Remove Backdrop Request received', event.detail);
        alert('LuigiClient.uxManager().removeBackdrop()');
      });
      compoundContainer.addEventListener(MFEventID.COLLAPSE_LEFT_NAV_REQUEST, (event) => {
        console.log('Collapse Left Side Nav Request received', event.detail);
        alert('LuigiClient.uxManager().collapseLeftSideNav()');
      });
      compoundContainer.addEventListener(
        MFEventID.SET_DOCUMENT_TITLE_REQUEST,
        (event) => {
          console.log('Set Document Title Request received', event.detail);
          compoundContainer.documentTitle = event.detail;
        },
      );
      compoundContainer.addEventListener(
        MFEventID.HIDE_LOADING_INDICATOR_REQUEST,
        (event) => {
          console.log('Hide Loading Indicator Request received', event.detail);
          alert('LuigiClient.uxManager().hideAppLoadingIndicator()');
        },
      );

      compoundContainer.addEventListener(MFEventID.ALERT_REQUEST, (event) => {
        console.log('event', event.detail);
        alert(event.detail.text);
        const settings = event.detail;
        alertSettings.settings = settings;
        showAnAlert(alertSettings, compoundContainer);
      });

      compoundContainer.addEventListener(MFEventID.ADD_SEARCH_PARAMS_REQUEST, (event) => {
        if (event) console.log(event.detail);
      });

      // linkManager listeners:
      // path exists
      compoundContainer.addEventListener(MFEventID.PATH_EXISTS_REQUEST, (event) => {
        console.log('Path Exists Request received', event.detail, event);
        // send back result with defined 'callback'
        // event: MFEventID.PathExistsEvent can be used as an event type to get the callback function
        event.callback(true);
      });

      // setViewGroup Data listener
      compoundContainer.addEventListener(
        MFEventID.SET_VIEW_GROUP_DATA_REQUEST,
        (event) => {
          console.log('Set View Group Data Request received', event.detail, event);
          alert(JSON.stringify(event.detail));
        },
      );

      const deferInitContainer = document.getElementById('defer-init-test');
      const deferInitButton = document.getElementById('defer-init-button');
      deferInitButton.addEventListener('click', function () {
        deferInitContainer.init();
      });
      deferInitContainer.compoundConfig = {
        renderer: {
          use: 'grid',
          config: {
            columns: '1fr 1fr',
            gap: '20px',
          },
        },
        children: [
          {
            viewUrl: './compound/defer-init-wc/compoundWCDeferInit1.js',
          },
          {
            viewUrl: './compound/defer-init-wc/compoundWCDeferInit2.js',
          },
        ],
      };

      const luigiClientInitContainer = document.getElementById('luigi-client-init-test');
      const luigiClientInitButton = document.getElementById('luigi-client-init-button');
      luigiClientInitButton.addEventListener('click', function () {
        console.log('luigi-client-init');
        luigiClientInitContainer.init();
      });

      luigiClientInitContainer.compoundConfig = {
        renderer: {
          use: 'grid',
          config: {
            columns: '1fr 1fr',
            gap: '20px',
          },
        },
        children: [
          {
            viewUrl: './compound/luigi-client-init-wc/luigi-client-init-wc.js',
            layoutConfig: {
              row: '1',
              column: '1 / -1',
            },
          },
        ],
      };

      document.querySelector('#luigi-update-context').addEventListener('click', () => {
        compoundContainer.updateContext({ newContextData: 'some data' });
        document.querySelector('#cc-ctx').innerHTML = JSON.stringify(
          compoundContainer.context,
        );
      });
    </script>
  </body>
</html>
